// pages/article/detail/index.js
import { saveMonitorhcDispose } from '../../service/api/api-dispose';
import { selectMonitorhcRecord,  } from '../../service/api/api-monitor';

Page({
  data: {
    id: '', // 文章ID
    details: null, // 详情数据
    html: '', // 文章HTML内容
    loading: false, // 加载状态
    showViolationDrawerVisible: false, // 问题词汇抽屉显示状态
    showDisposeDrawerVisible: false, // 处置操作抽屉显示状态
    violationWords: [], // 所有问题词汇
    errorItems: [], // 错误类型问题
    checkItems: [], // 核对类型问题
    type: 0,
    disposeForm: {
      scheme: '1',
      content: ''
    }
  },

  onLoad(options) {
    if (options.id) {
      this.setData({
        id: options.id,
        type: options.type
      });
      this.loadArticleDetail();
    } else {
      wx.showToast({
        title: '文章ID不存在',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 加载文章详情
  async loadArticleDetail() {
    this.setData({ loading: true });

    try {
      const res = await selectMonitorhcRecord({
        id: this.data.id
      });

      if (res.code === 0) {
        let html = res.data?.greenText?.html || '';

        // 处理HTML中的样式类名 - 根据inspectCategory区分错误和核对类型
        if (res.data?.greenText?.inspectWords && res.data.greenText.inspectWords.length > 0) {
          // 先移除所有现有的样式类名
          html = html
            .replaceAll(`class="word-mark-error-major"`, '')
            .replaceAll(`class="word-mark-error-critical"`, '')
            .replaceAll(`class="word-mark-error-blocker"`, '')
            .replaceAll(`class="word-mark-check-major"`, '')
            .replaceAll(`class="word-mark-check-critical"`, '')
            .replaceAll(`class="word-mark-check-blocker"`, '');

          // 根据inspectCategory属性动态设置样式
          res.data.greenText.inspectWords.forEach(item => {
            if (item.positioningId) {
              const wordId = `word${item.positioningId}`;
              let style = '';

              if (item.inspectCategory === '错误') {
                style = `style="background-color: #ffccc7; color: #ff4d4f;"`;
              } else if (item.inspectCategory === '可疑') {
                style = `style="background-color: #fffbe6; color: #faad14;"`;
              }

              if (style) {
                // 先移除可能存在的style属性
                const styleRegex = /style="[^"]*"/g;
                html = html.replace(new RegExp(`id="${wordId}"[^>]*`, 'g'), (match) => {
                  return match.replace(styleRegex, '');
                });

                // 添加新的style属性
                html = html.replace(`id="${wordId}"`, `id="${wordId}" ${style}`);
              }
            }
          });
        }

        // 处理问题词汇数据
        const processedData = this.processViolationData(res.data?.greenText?.inspectWords);

        this.setData({
          details: res.data,
          html: html,
          violationWords: processedData.allWords,
          errorItems: processedData.errorItems,
          checkItems: processedData.checkItems,
          loading: false
        });
      } else {
        throw new Error(res.message || '加载失败');
      }
    } catch (error) {
      console.error('加载详情失败:', error);
      this.setData({ loading: false });
      wx.showToast({
        title: '加载详情失败',
        icon: 'none'
      });
    }
  },

  // 处理问题词汇数据
  processViolationData(inspectWords) {
    if (!inspectWords || !Array.isArray(inspectWords)) {
      return { allWords: [], errorItems: [], checkItems: [] };
    }

    const errorItems = [];
    const checkItems = [];

    const allWords = inspectWords.map(item => {
      // 处理词汇文本
      let wordText = '';
      if (typeof item === 'object' && item !== null) {
        wordText = item.text || item.word || item.content || JSON.stringify(item);
      } else {
        wordText = item;
      }

      // 分类处理
      const processedItem = {
        id: item.id || Math.random().toString(36).substr(2, 9),
        content: wordText,
        inspectCategory: item.inspectCategory || '可疑',
        inspectType: item.inspectType || '',
        inspectTypeEn: item.inspectTypeEn || '',
        lookup: item.lookup || '',
        positioningId: item.positioningId || '',
        repair: item.repair || 0,
        ignore: item.ignore || 0,
        click: item.click || 0
      };

      // 分类
      if (processedItem.inspectCategory === '错误') {
        errorItems.push(processedItem);
      } else {
        checkItems.push(processedItem);
      }

      return processedItem;
    }).filter(item => item.content && item.content !== '[object Object]');

    return {
      allWords: allWords,
      errorItems: errorItems,
      checkItems: checkItems
    };
  },

  // 显示问题词汇抽屉
  showViolationDrawer() {
    this.setData({
      showViolationDrawerVisible: true
    });
  },

  // 隐藏问题词汇抽屉
  hideViolationDrawer() {
    this.setData({
      showViolationDrawerVisible: false
    });
  },

  // 显示处置操作抽屉
  showDisposeDrawer() {
    this.setData({
      showDisposeDrawerVisible: true
    });
  },

  // 隐藏处置操作抽屉
  hideDisposeDrawer() {
    this.setData({
      showDisposeDrawerVisible: false
    });
  },

  // 处置方案选择变化
  onSchemeChange(e) {
    this.setData({
      'disposeForm.scheme': e.detail.value
    });
  },

  // 处置内容输入
  onContentInput(e) {
    this.setData({
      'disposeForm.content': e.detail.value
    });
  },

  // 提交处置
  async submitDispose() {
    const { scheme, content } = this.data.disposeForm;
    
    if (!content.trim()) {
      wx.showToast({
        title: '请输入处置内容',
        icon: 'none'
      });
      return;
    }

    try {
      const res = await saveMonitorhcDispose({
        includeRecordId: this.data.id,
        scheme: scheme, // 处置完成状态
        content: content.trim()
      });

      if (res.code === 0) {
        wx.showToast({
          title: '处置成功',
          icon: 'success'
        });
        
        this.setData({
          showDisposeDrawerVisible: false,
          'disposeForm.content': ''
        });
        
        // 重新加载详情数据
        this.loadArticleDetail();
      } else {
        throw new Error(res.message || '处置失败');
      }
    } catch (error) {
      console.error('处置失败:', error);
      wx.showToast({
        title: '处置失败',
        icon: 'none'
      });
    }
  },

  // 复制链接
  copyUrl(e) {
    const url = e.currentTarget.dataset.url;
    if (url) {
      wx.setClipboardData({
        data: url,
        success: () => {
          wx.showToast({
            title: '链接已复制'
          });
        }
      });
    }
  },

  // 返回列表
  goBack() {
    wx.navigateBack();
  },

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return '';
    return timeStr.replace('T', ' ').substring(0, 16);
  },

  // 计算属性：是否有问题词汇
  get hasViolationWords() {
    return this.data.violationWords && this.data.violationWords.length > 0;
  },

  // 获取状态类名
  getStatusClass(state) {
    if (state === undefined || state === 0) {
      return 'status-normal';
    } else if (state === 1) {
      return 'status-warning';
    } else {
      return 'status-problem';
    }
  },

  // 获取状态文本
  getStatusText(state) {
    if (state === undefined || state === 0) {
      return '正常';
    } else if (state === 1) {
      return '警告';
    } else {
      return '问题';
    }
  },

  // 获取处置状态类名
  getDisposeClass(disposeState) {
    if (disposeState === 1) {
      return 'dispose-processing';
    } else if (disposeState === 2) {
      return 'dispose-warning';
    } else if (disposeState === 3) {
      return 'dispose-success';
    } else {
      return 'dispose-default';
    }
  },

  // 获取处置状态文本
  getDisposeText(disposeState) {
    if (disposeState === 1) {
      return '无需处置';
    } else if (disposeState === 2) {
      return '需要处置';
    } else if (disposeState === 3) {
      return '处置完成';
    } else {
      return '未处置';
    }
  },

  // 获取处置方案文本
  getDisposeSchemeText(scheme) {
    if (scheme === 1) {
      return '不需要处理';
    } else if (scheme === 2) {
      return '下架不再发稿';
    } else if (scheme === 3) {
      return '下架修改重新发稿';
    } else {
      return '其他方案';
    }
  }
});